package com.sunshine.lnuplus.ui.activity

import android.app.Activity
import android.app.TimePickerDialog
import android.content.Context
import android.content.DialogInterface
import android.content.SharedPreferences
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.TimePicker
import androidx.appcompat.widget.AppCompatEditText
import com.google.android.material.datepicker.MaterialCalendar
import com.google.android.material.datepicker.MaterialDatePicker
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textfield.TextInputLayout
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.base.BaseActivity
import com.sunshine.lnuplus.model.InitData
import com.sunshine.lnuplus.utils.DateUtils
import com.sunshine.lnuplus.utils.StatusBarUtils
import com.sunshine.lnuplus.view.DialogWithView
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.activity_lesson_time.*
import kotlinx.android.synthetic.main.item_day.*

class LessonTimeActivity : BaseActivity() {

    private lateinit var spEdit: SharedPreferences.Editor

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_lesson_time)

        spEdit = getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE).edit()
        initView()
    }

    private fun initView() {
        StatusBarUtils.setStatusBarWithColor(this, color)
        title = "设置上下课时间"

        var lessonTime = 50
        button_auto_set.setOnClickListener {
            checkBox_auto_set.isChecked = !checkBox_auto_set.isChecked
        }
        button_time_length.setOnClickListener {
            val view = LayoutInflater.from(this).inflate(R.layout.dialog_calender_time, null, false)
            view.findViewById<TextInputLayout>(R.id.til_count_down_time).hint = "请输入每节课时长"
            val dialog = DialogWithView.newInstance(
                view,
                "请输入每节课的时长",
                false,
                DialogInterface.OnClickListener { _, _ ->
                    try {
                        lessonTime = view.findViewById<AppCompatEditText>(R.id.edit_calender_time).text.toString().toInt()
                        button_time_length.text = "每节课时长:${lessonTime}分钟"
                    }catch (e: Exception){
                        Toasty.error(this, "输入有问题呀~").show()
                    }
                },
                null)
            dialog.show(supportFragmentManager, "")
        }

        for(jie in 1..InitData.lessonStyle.count){
            try {
                InitData.lessonStyle.lessonTime[jie - 1]
            }catch (e: Exception){
                InitData.lessonStyle.lessonTime.add(" \n ")
            }finally {
                val view = LayoutInflater.from(this).inflate(R.layout.item_lesson_time, lesson_time_view, false)
                view.findViewById<TextView>(R.id.lesson_time_jie).text = "第${jie}节"
                view.findViewById<TextView>(R.id.lesson_time_time).text = "${InitData.lessonStyle.lessonTime[jie - 1].split("\n")[0]} - ${InitData.lessonStyle.lessonTime[jie - 1].split("\n")[1]}"
                view.findViewById<View>(R.id.lesson_time_click_view).setOnClickListener {
                    val timeView = TimePicker(this)
                    var hour = 0
                    var minute = 0
                    timeView.setOnTimeChangedListener { _, hourOfDay, min ->
                        hour = hourOfDay
                        minute = min
                    }
                    DialogWithView.newInstance(
                        timeView,
                        "请选择上课时间",
                        true,
                        DialogInterface.OnClickListener { _, _ ->
                            val startHString = if(hour < 10) "0$hour" else hour.toString()
                            val startMString = if(minute < 10) "0$minute" else minute.toString()
                            if(checkBox_auto_set.isChecked){
                                var endH = lessonTime / 60 + hour
                                var endM = lessonTime % 60 + minute
                                if(endM >= 60){
                                    endH++
                                    endM-=60
                                }
                                if(endH > 24) endH -= 24
                                val endHString = if(endH < 10) "0$endH" else endH.toString()
                                val endMString = if(endM < 10) "0$endM" else endM.toString()
                                view.findViewById<TextView>(R.id.lesson_time_time).text = "$startHString:$startMString - $endHString:$endMString"
                                InitData.lessonStyle.lessonTime[jie - 1] = "$startHString:$startMString\n$endHString:$endMString"
                            }else{
                                DialogWithView.newInstance(
                                    timeView,
                                    "请选择下课时间",
                                    true,
                                    DialogInterface.OnClickListener { _, _ ->
                                        val endHString = if(hour < 10) "0$hour" else hour.toString()
                                        val endMString = if(minute < 10) "0$minute" else minute.toString()
                                        view.findViewById<TextView>(R.id.lesson_time_time).text = "$startHString:$startMString - $endHString:$endMString"
                                        InitData.lessonStyle.lessonTime[jie - 1] = "$startHString:$startMString\n$endHString:$endMString"
                                    },
                                    null
                                ).show(supportFragmentManager, "")
                            }
                        },
                        null
                    ).show(supportFragmentManager, "")
                }
                lesson_time_view.addView(view)
            }
        }

        getToolBar()?.setNavigationOnClickListener {
            var lessonTime = ""
            InitData.lessonStyle.lessonTime.forEach {
                if(it.isNotBlank()) lessonTime += "$it|"
            }
            spEdit.putString("lesson_time", lessonTime)
            setResult(Activity.RESULT_OK)
            supportFinishAfterTransition()
        }

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK && event?.action == KeyEvent.ACTION_DOWN) {
            var lessonTime = ""
            InitData.lessonStyle.lessonTime.forEach {
                if(it.isNotBlank()) lessonTime += "$it|"
            }
            spEdit.putString("lesson_time", lessonTime)
            setResult(Activity.RESULT_OK)
            finish()
            true
        } else {
            super.onKeyDown(keyCode, event)
        }
    }

    override fun onPause() {
        super.onPause()
        spEdit.apply()
    }
}
